import React, { useState, useCallback, useRef } from 'react';
import {
  View,
  FlatList,
  Dimensions,
  ActivityIndicator,
  StyleSheet,
  RefreshControl,
  Platform,
  Text,
} from 'react-native';
import { useRouter } from 'expo-router';
import { useTheme } from '../../hooks/useTheme';
import { artworkService } from '../../utils/api/services';
import { ArtworkResponse, PaginatedData } from '../../utils/api/types';
import ExploreArtworkCard from '../../components/explore/ExploreArtworkCard';

const { width, height } = Dimensions.get('window');

export default function ExploreScreen() {
  const { theme } = useTheme();
  const [artworks, setArtworks] = useState<ArtworkResponse[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const pageRef = useRef(1);
  const PAGE_SIZE = 10;
  const flatListRef = useRef<FlatList>(null);

  const loadArtworks = useCallback(async (refresh = false) => {
    if (isLoading || (!hasMore && !refresh)) return;

    try {
      setIsLoading(true);
      const page = refresh ? 1 : pageRef.current;

      console.log('Loading artworks, page:', page);
      const response = await artworkService.listArtworks({
        limit: PAGE_SIZE,
        offset: (page - 1) * PAGE_SIZE,
      });

      console.log('API Response:', JSON.stringify(response, null, 2));
      if (response.code !== 200) {
        throw new Error(`API error: ${response.message}`);
      }

      const paginatedData = response.data as unknown as PaginatedData<ArtworkResponse>;
      if (!paginatedData?.items) {
        console.log('No items received');
        setArtworks(refresh ? [] : artworks);
        setHasMore(false);
        return;
      }

      const newArtworks = paginatedData.items;
      console.log('New artworks:', JSON.stringify(newArtworks, null, 2));
      
      if (refresh) {
        setArtworks(newArtworks);
        pageRef.current = 1;
      } else {
        setArtworks(prev => [...prev, ...newArtworks]);
        pageRef.current = page + 1;
      }

      setHasMore(newArtworks.length === PAGE_SIZE);
    } catch (error) {
      console.error('Failed to load artworks:', error);
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  }, []);

  const handleRefresh = useCallback(() => {
    setIsRefreshing(true);
    setHasMore(true);
    loadArtworks(true);
  }, [loadArtworks]);

  const handleLoadMore = useCallback(() => {
    if (!isLoading && hasMore) {
      loadArtworks();
    }
  }, [isLoading, hasMore, loadArtworks]);

  const renderItem = useCallback(({ item }: { item: ArtworkResponse }) => {
    console.log('Rendering item:', item);
    return <ExploreArtworkCard artwork={item} />;
  }, []);

  const renderFooter = useCallback(() => {
    if (!isLoading) return null;

    return (
      <View style={styles.footer}>
        <ActivityIndicator size="large" color={theme.colors.primary} />
      </View>
    );
  }, [isLoading, theme]);

  const getItemLayout = useCallback((_: any, index: number) => ({
    length: height,
    offset: height * index,
    index,
  }), []);

  // 首次加载
  React.useEffect(() => {
    console.log('Component mounted, loading artworks...');
    loadArtworks(true);
  }, []);

  return (
    <View style={[styles.container, { backgroundColor: '#000' }]}>
      {artworks.length === 0 && !isLoading ? (
        <View style={styles.emptyContainer}>
          <Text style={[styles.emptyText, { color: '#fff' }]}>
            暂无作品
          </Text>
        </View>
      ) : (
        <FlatList
          ref={flatListRef}
          data={artworks}
          renderItem={renderItem}
          keyExtractor={item => item.id.toString()}
          onEndReached={handleLoadMore}
          onEndReachedThreshold={0.2}
          refreshControl={
            <RefreshControl
              refreshing={isRefreshing}
              onRefresh={handleRefresh}
              tintColor="#fff"
            />
          }
          ListFooterComponent={renderFooter}
          removeClippedSubviews={Platform.OS !== 'web'}
          maxToRenderPerBatch={3}
          windowSize={5}
          showsVerticalScrollIndicator={false}
          style={styles.list}
          contentContainerStyle={[
            styles.listContent,
            artworks.length === 0 && styles.emptyList
          ]}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  list: {
    flex: 1,
  },
  listContent: {
    paddingVertical: 8,
  },
  footer: {
    padding: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyText: {
    fontSize: 16,
  },
  emptyList: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
